import { defineStore } from 'pinia'
import { login, register, getInfo, logout as apiLogout } from '../../api/login'
import { ElMessage } from 'element-plus'

// 直接在文件中定义UserInfo接口，避免导入问题
interface UserInfo {
  permissions: string[];
  roles: string[];
  user: {
    userId: number;
    deptId: number;
    userName: string;
    nickName: string;
    email: string;
    phonenumber: string;
    avatar: string;
    admin: boolean;
    loginDate: string;
  };
}

interface UserState {
  token: string | null
  username: string
  nickname: string
  avatar: string
  roles: string[]
  permissions: string[]
  loading: boolean
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: localStorage.getItem('Admin-Token'),
    username: '',
    nickname: '',
    avatar: '',
    roles: [],
    permissions: [],
    loading: false
  }),

  getters: {
    // 是否已登录
    isLoggedIn: (state) => !!state.token,
    // 获取用户显示名称
    displayName: (state) => state.nickname || state.username || '用户',
    // 获取用户头像或首字母
    avatarOrInitial: (state) => {
      if (state.avatar) return state.avatar
      const displayName = state.nickname || state.username || '用户'
      return displayName.charAt(0).toUpperCase()
    }
  },

  actions: {
    // 登录
    async login(userInfo: any) {
      this.loading = true
      try {
        const response = await login(userInfo)
        
        // 存储token
        this.setToken(response.data?.access_token || '')
        
        // 获取用户信息
        await this.getUserInfo()
        
        return response
      } catch (error) {
        throw error
      } finally {
        this.loading = false
      }
    },

    // 注册
    async register(userInfo: any) {
      this.loading = true
      try {
        const response = await register(userInfo)
        ElMessage.success('注册成功')
        return response
      } catch (error) {
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await getInfo()
        const userData: UserInfo = response.data || { permissions: [], roles: [], user: { userId: 0, deptId: 0, userName: '', nickName: '', email: '', phonenumber: '', avatar: '', admin: false, loginDate: '' } }
        
        // 设置用户信息
        if (userData.user) {
          this.username = userData.user.userName || ''
          this.nickname = userData.user.nickName || userData.user.userName || ''
          this.avatar = userData.user.avatar || ''
          this.roles = userData.roles || []
          this.permissions = userData.permissions || []
        }
        
        return userData
      } catch (error) {
        // 获取用户信息失败，可能是token过期，清除token
        this.logout()
        throw error
      }
    },

    // 设置token
    setToken(token: string) {
      this.token = token
      localStorage.setItem('Admin-Token', token)
    },

    removeToken() {
      this.token = null
      localStorage.removeItem('Admin-Token')
      localStorage.removeItem('username')
      localStorage.removeItem('password')
    },

    async logout() {
      try {
        await apiLogout()
      } finally {
        // 无论API调用成功与否，都清除本地状态
        this.removeToken()
        this.username = ''
        this.nickname = ''
        this.avatar = ''
        this.roles = []
        this.permissions = []
      }
    },

    updateUserInfo(userData: Partial<UserState>) {
      Object.assign(this, userData)
    }
  }
})
